/**
 * @file index.js
 * @author swan
 */
const app = getApp()
var Api = require('../../utils/api.js');
var util = require('../../utils/util.js');
var bdApi = require('../../utils/bdApi.js');
var Auth = require('../../utils/auth.js');
var bdRequest = require('../../utils/bdRequest.js')
import config from '../../utils/config.js'
var pageCount = config.getPageCount;
var WxParse = require('../../wxParse/wxParse.js');
import seoConfig from '../../seoConfig/config.js'
let isFocusing = false
import { ModalView } from '../../component/modal-view/modal-view.js'


Page({
    data: {
        url: '',
        src: '',
        controls: true,
        showVideo: false,
        condition: false,
        title: '文章内容',
        detail: {},
        commentsList: [],
        ChildrenCommentsList: [],
        commentCount: '',
        detailDate: '',
        commentValue: '',
        wxParseData: {},
        display: 'none',
        page: 1,
        isLastPage: false,
        parentID: "0",
        focus: false,
        placeholder: "评论...",
        postID: null,
        scrollHeight: 0,
        postList: [],
        link: '',
        dialog: {
            title: '',
            content: '',
            hidden: true
        },
        content: '',
        isShow: false, //控制menubox是否显示
        isLoad: true, //解决menubox执行一次  
        menuBackgroup: false,
        likeImag: "like.png",
        likeList: [],
        likeCount: 0,
        displayLike: 'block',
        replayTemplateId: config.getReplayTemplateId,
        userid: "",
        toFromId: "",
        commentdate: "",
        flag: 1,
        logo: config.getLogo,
        enableComment: false,
        isLoading: false,
        total_comments: 0,
        isLoginPopup: false,
        openid: "",
        userInfo: {},
        system: '',
        show: false,
        nextPost: {
            img: '',
            date: ''
        },
        previousPost: {
            img: '',
            date: ''
        },
        commentParam: {
            snid: '',   // 文章的唯一标识，与path参数一一对应，例如值为'20200101'
            openid: '', // 用户身份唯一表示
            path: '', // 文章页面地址，用于消息推送等流量入口跳转回访，与snid参数一一对应，例如'/page/home/index?snid=20200101'
            title: '',   // 文章标题
            content: '', // 文章内容
            images: [] // 文章图集
        },
         selector: [{
            name:'档案吧'
        }, {
            name:'个人档案吧'
        }],
        rangeKey: ['档案吧'],
        arrIndex: 0
    },

    // getOpenid() {
    //     if (swan.getStorageSync('openid')) {
    //         this.setData('commentParam.openid', swan.getStorageSync(openid));
    //     } else {
    //         swan.login({
    //             success: res => {
    //                 swan.request({
    //                     url: 'https://spapi.baidu.com/oauth/jscode2sessionkey',
    //                     method: 'POST',
    //                     header: {
    //                         'content-type': 'application/x-www-form-urlencoded'
    //                     },
    //                     data: {
    //                         code: res.code,
    //                         // 这里是获取你的openid
    //                         // client_id = AppKey, sk = AppSecret
    //                         client_id: 'uUVbLdiB8nRV8tGwnm984dVxQIr2c20U', // eslint-disable-line
    //                         sk: 'vRLbU7GAlr8LNiL2cSCRFs9R5nYn9Xxp'
    //                     },
    //                     success: res => {
    //                         if (res.statusCode === 200) {
    //                             swan.setStorageSync('openid', res.data.openid);
    //                             this.setData('commentParam.openid', res.data.openid);
    //                         }
    //                     }
    //                 });
    //             }
    //         });
    //     }

    // },

    controls() {
        this.setData({
            controls: !this.data.controls
        });
    },
    islogin() {
        var self = this;
        Auth.setUserInfoData(self);
        Auth.checkLogin(self);
    },
    playPhone() {
        swan.makePhoneCall({
            phoneNumber: '4009687088' //仅为示例，并非真实的电话号码
        });
    },
    callTieba() { // 自定义名字即可
        const url = this.data.url ? '&url=' + this.data.url : '';
        const id = this.data.postID ? this.data.postID : ''
        const link =id ? '/pages/detail/detail?id=' + id + url : '/pages/index/index';
        console.log(link)
        let data = {
            third_app_id: 'uUVbLdiB8nRV8tGwnm984dVxQIr2c20U', // 历史原因，这里传入的是小程序的key，非小程序id
            third_app_name: "办得爽档案查询网", // 小程序名字
            third_app_avatar: 'https://www.bds110.com/wp-content/uploads/bdsmp-dacx/bdslogo.png', // 小程序logo
            third_app_pic: this.data.detail.content_first_image ? this.data.detail.content_first_image : this.data.detail.postImageUrl, // 发帖时展示的预览图片，可根据分享的不同页面定制
            third_app_link: link, // 文章页面地址，用于消息推送等流量入口跳转回访，与snid参数一一对应，例如'/page/home/index?snid=20200101' // 点击小程序分享帖后具体要跳入的小程序页面。
        }
        let dataStr = encodeURIComponent(JSON.stringify(data)); // 序列化一下
        swan.navigateToSmartProgram({ // 调用小程序的api
            appKey: 'flFqXclepWs7RdugAszy9eERL7G5dS0I', // 固定的，不要修改
            path: `/pages/frshistory/frshistory?extradata=${dataStr}`, // 固定的，不要修改
            extraData: {
                from: 'bdsdacx' // 小程序标识，统计用的，请尽量使用英文数字，不对中文兼容
            },
            success(res) {
                // 打开成功你的回调
                console.log(res,'打开成功你的回调')
            }
        })
    },
    selectorChange(e) {
        console.log('picker-selector changed，值为', e.detail.value);
        this.setData('arrIndex', e.detail.value);
        this.callTieba()
    },
    // 跳转至查看小程序列表页面或文章详情页
    redictAppDetail: function (e) {
        console.log('查看文章');
        var id = e.currentTarget.id;
        var redicttype = e.currentTarget.dataset.redicttype;
        var url = e.currentTarget.dataset.url == null ? '' : e.currentTarget.dataset.url;
        var appid = e.currentTarget.dataset.appid == null ? '' : e.currentTarget.dataset.appid;

        if (redicttype == 'detailpage')//跳转到内容页
        {
            url = '../detail/detail?id=' + id;
            swan.navigateTo({
                url: url
            })
        }
        if (redicttype == 'apppage') {//跳转到小程序内部页面         
            swan.navigateTo({
                url: url
            })
        }
        else if (redicttype == 'webpage')//跳转到web-view内嵌的页面
        {
            url = '../webpage/webpage?url=' + url;
            swan.navigateTo({
                url: url
            })
        }
        else if (redicttype == 'miniapp')//跳转到其他app
        {
            swan.navigateToMiniProgram({
                appId: appid,
                envVersion: 'release',
                path: url,
                success(res) {
                    // 打开成功
                },
                fail: function (res) {
                    console.log(res);
                }
            })
        }
    },
    onLoad: function (options) {
        var self = this;
        if (options.url) {
            this.setData({
                url: options.url
            })
        }
        self.getEnableComment(); //是否开启评论
        self.fetchDetailData(options.id);
        self.fetchVideoAddress(options.id);
        // Auth.setUserInfoData(self);
        // Auth.checkLogin(self);
        swan.getSystemInfo({
            success: function (t) {
                var system = t.system.indexOf('iOS') != -1 ? 'iOS' : 'Android';
                self.setData({
                    system: system
                });
            }
        })
        // console.log(ModalView)
        new ModalView
        console.log('过了')

    },
    showLikeImg: function () {
        var self = this;
        var flag = false;
        var _likes = self.data.detail.avatarurls;
        var likes = [];
        for (var i = 0; i < _likes.length; i++) {
            var avatarurl = "https://www.bds110.com/wp-content/uploads/bdsmp-dacx/gravatar.png";
            if (_likes[i].avatarurl.indexOf('wx.qlogo.cn') != -1) {
                avatarurl = _likes[i].avatarurl;
            }
            likes[i] = avatarurl;
        }
        var temp = likes;
        self.setData({
            likeList: likes
        });
    },
    onReachBottom: function () {
        var self = this;
        if (!self.data.isLastPage) {
            console.log('当前页' + self.data.page);
            self.fetchCommentData();
            self.setData({
                page: self.data.page + 1,
            });
        } else {
            console.log('评论已经是最后一页了');
        }

    },
    onShareAppMessage: function (res) {
        this.ShowHideMenu();
        console.log(res);
        return {
            title: '分享"' + config.getWebsiteName + '"的文章：' + this.data.detail.title.rendered,
            path: 'pages/detail/detail?id=' + this.data.detail.id,
            imageUrl: this.data.detail.post_thumbnail_image,
            success: function (res) {
                // 转发成功
                console.log(res);
            },
            fail: function (res) {
                console.log(res);
                // 转发失败
            }
        }
    },
    gotowebpage: function () {
        var self = this;
        self.ShowHideMenu();
        var minAppType = config.getMinAppType;
        var url = '';
        if (minAppType == "0") {
            var url = '../webpage/webpage';
            swan.navigateTo({
                url: url + '?url=' + self.data.link
            })
        } else {
            self.copyLink(self.data.link);
        }

    },
    copyLink: function (url) {
        //this.ShowHideMenu();
        swan.setClipboardData({
            data: url,
            success: function (res) {
                swan.getClipboardData({
                    success: function (res) {
                        swan.showToast({
                            title: '链接已复制',
                            image: 'https://www.bds110.com/wp-content/uploads/bdsmp-dacx/link.png',
                            duration: 2000
                        })
                    }
                })
            }
        })
    },
    clickLike: function (e) {
        var id = e.target.id;
        var self = this;
        if (id == 'likebottom') {
            this.ShowHideMenu();
        }

        if (self.data.openid) {
            var data = {
                openid: self.data.openid,
                postid: self.data.postID
            };

            var url = Api.postLikeUrl();
            var postLikeRequest = bdRequest.postRequest(url, data);
            postLikeRequest
                .then(response => {
                    console.log(111)
                    if (response.data.status == '200') {
                        var _likeList = []
                        var _like = self.data.userInfo.avatarUrl;
                        _likeList.push(_like);
                        var tempLikeList = _likeList.concat(self.data.likeList);
                        var _likeCount = parseInt(self.data.likeCount) + 1;
                        self.setData({
                            likeList: tempLikeList,
                            likeCount: _likeCount,
                            displayLike: 'block'
                        });
                        swan.showToast({
                            title: '谢谢点赞',
                            icon: 'success',
                            duration: 900,
                            success: function () { }
                        })
                    } else if (response.data.status == '501') {
                        console.log(response.data.message);
                        swan.showToast({
                            title: '谢谢，已赞过',
                            icon: 'success',
                            duration: 900,
                            success: function () { }
                        })
                    } else {
                        console.log(response.data.message);

                    }
                    self.setData({
                        likeImag: "like-on.png"
                    });
                })
        } else {
            console.log(1233444)
            Auth.checkSession(self, 'isLoginNow');

        }
    },
    getIslike: function () { //判断当前用户是否点赞
        var self = this;
        if (self.data.openid) {
            var data = {
                openid: self.data.openid,
                postid: self.data.postID
            };
            var url = Api.postIsLikeUrl();
            var postIsLikeRequest = bdRequest.postRequest(url, data);
            postIsLikeRequest
                .then(response => {
                    if (response.data.status == '200') {
                        self.setData({
                            likeImag: "like-on.png"
                        });

                        console.log("已赞过");
                    }

                })

        }
    },

    goHome: function () {
        swan.switchTab({
            url: '../index/index'
        })
    },
    praise: function () {
        this.ShowHideMenu();
        var self = this;
        var minAppType = config.getMinAppType;
        var system = self.data.system;
        if (minAppType == "0" && system == 'Android') {
            if (self.data.openid) {

                swan.navigateTo({
                    url: '../pay/pay?flag=1&openid=' + self.data.openid + '&postid=' + self.data.postID
                })
            } else {
                Auth.checkSession(self, 'isLoginNow');
            }
        } else {

            var src = config.getZanImageUrl;
            swan.previewImage({
                urls: [src],
            });

        }
    },

    //获取是否开启评论设置
    getEnableComment: function (id) {
        var self = this;
        var getEnableCommentRequest = bdRequest.getRequest(Api.getEnableComment());
        getEnableCommentRequest
            .then(response => {
                if (response.data.enableComment != null && response.data.enableComment != '') {
                    if (response.data.enableComment === "1") {
                        self.setData({
                            enableComment: true
                        });
                    } else {
                        self.setData({
                            enableComment: false
                        });
                    }

                };

            });
    },
    setConfig(seo) {
        swan.setPageInfo && swan.setPageInfo(seo)
    },
    // 获得视频地址
    fetchVideoAddress(id) {
        var getPostvideo = bdRequest.getRequest(Api.getPostVideo(id));
        getPostvideo.then(res => {
            try {
                var src = res.data.meta_value.split('s:70:\"')[1].split('\";')[0]
                if (src) {
                    this.setData({
                        src: src
                    })
                }
            } catch (e) {
            }



        })
    },
    //获取文章内容
    fetchDetailData: function (id) {
        var self = this;
        var getPostDetailRequest = bdRequest.getRequest(Api.getPostByID(id));
        var res;
        var _displayLike = 'block';
        getPostDetailRequest
            .then(response => {
                res = response;
                self.setData({ content: WxParse.bdParse('article', 'html', response.data.content.rendered, self, 5), })
                // WxParse.bdParse('article', 'html', response.data.content.rendered, self, 5);
                // if (response.data.total_comments != null && response.data.total_comments != '') {
                //     self.setData({
                //         commentCount: "有" + response.data.total_comments + "条评论"
                //     });
                // };
                var _likeCount = response.data.like_count;
                if (response.data.like_count != '0') {
                    _displayLike = "block"
                }
                // 获得下一篇文章信息
                if (response.data.next_post_id) {
                    bdRequest.getRequest(Api.getPostByID(response.data.next_post_id)).then(next => {
                        this.setData({
                            nextPost: {
                                img: next.data.post_medium_image,
                                date: util.cutstr(next.data.date, 10, 1)
                            }
                        })
                    });
                }

                // 获得上一票文章信息
                if (response.data.previous_post_id) {
                    bdRequest.getRequest(Api.getPostByID(response.data.previous_post_id)).then(previous => {
                        console.log('previous', previous)
                        this.setData({
                            previousPost: {
                                img: previous.data.post_medium_image,
                                date: util.cutstr(previous.data.date, 10, 1)
                            }
                        })
                    });
                }
                const images = []
                res.data.post_all_images.forEach((item) => {
                    images.push(item.imagesurl)
                })
                console.log(images)
                const url = this.data.url ? '&url=' + this.data.url : ''
                self.setData({
                    commentParam: {
                        snid: id,   // 文章的唯一标识，与path参数一一对应，例如值为'20200101'
                        openid: swan.getStorageSync('openid'), // 用户身份唯一表示
                        path: 'pages/detail/detail?id=' + id + url, // 文章页面地址，用于消息推送等流量入口跳转回访，与snid参数一一对应，例如'/page/home/index?snid=20200101'
                        title: response.data.title.rendered,   // 文章标题
                        content: response.data.content.rendered, // 文章内容
                        images: images  // 文章图集
                    },
                    detail: response.data,
                    likeCount: _likeCount,
                    postID: id,
                    link: response.data.link,
                    detailDate: util.cutstr(response.data.date, 10, 1),
                    //wxParseData: WxParse('md',response.data.content.rendered)
                    // wxParseData: WxParse.wxParse('article', 'html', response.data.content.rendered, self, 5),
                    display: 'block',
                    displayLike: _displayLike,
                    total_comments: response.data.total_comments

                });
                // 调用API从本地缓存中获取阅读记录并记录
                var logs = swan.getStorageSync('readLogs') || [];
                // 过滤重复值
                if (logs.length > 0) {
                    logs = logs.filter(function (log) {
                        return log[0] !== id;
                    });
                }
                // 如果超过指定数量
                if (logs.length > 19) {
                    logs.pop(); //去除最后一个
                }
                logs.unshift([id, response.data.title.rendered]);
                swan.setStorageSync('readLogs', logs);
                //end 
                console.log(this.data.commentParam)

            })
            .then(response => {
                swan.setNavigationBarTitle({
                    title: res.data.title.rendered
                });
                console.log(util.getHtmlText(res.data.previous_post_title))
                swan.setPageInfo({
                    title: res.data.title.rendered + '-办得爽',
                    keywords: res.data.title.rendered,
                    description: util.getHtmlText(res.data.previous_post_title) ? util.getHtmlText(res.data.previous_post_title) : '办得爽为您提供档案查询，档案补办，档案托管，档案存放等相关专题知识分享，档案丢了怎么办？档案托管怎么办理？这些档案问题都知道怎么解决吗？',
                    success: function () {
                        console.log('页面基础信息设置完成');
                    }
                })

            })
            .then(response => {
                var tagsArr = [];
                tagsArr = res.data.tags
                var tags = "";
                for (var i = 0; i < tagsArr.length; i++) {
                    if (i == 0) {
                        tags += tagsArr[i];
                    } else {
                        tags += "," + tagsArr[i];

                    }
                }
                if (tags != "") {
                    var getPostTagsRequest = bdRequest.getRequest(Api.getPostsByTags(id, tags));
                    getPostTagsRequest
                        .then(response => {
                            self.setData({
                                postList: response.data
                            });

                        })

                }
            }).then(response => { //获取点赞记录
                self.showLikeImg();
            }).then(resonse => {
                if (self.data.openid) {
                    Auth.checkSession(self, 'isLoginLater');
                }

            }).then(response => { //获取是否已经点赞
                if (self.data.openid) {
                    self.getIslike();
                }
            })
            .catch(function (error) {
                self.setData({
                    condition: true,
                    displayLike: "none"
                })
                console.log('error: ' + error);
            })
    },
    //给a标签添加跳转和复制链接事件
    bdParseTagATap: function (e) {
        var self = this;
        var href = e.currentTarget.dataset.src;
        console.log(href);
        var domain = config.getDomain;
        //可以在这里进行一些路由处理
        if (href.indexOf(domain) == -1) {
            swan.setClipboardData({
                data: href,
                success: function (res) {
                    swan.getClipboardData({
                        success: function (res) {
                            swan.showToast({
                                title: '链接已复制',
                                //icon: 'success',
                                image: 'https://www.bds110.com/wp-content/uploads/bdsmp-dacx/link.png',
                                duration: 2000
                            })
                        }
                    })
                }
            })
        } else {
            var slug = util.GetUrlFileName(href, domain);
            if (slug == 'index') {
                swan.switchTab({
                    url: '../index/index'
                })
            } else {
                var getPostSlugRequest = bdRequest.getRequest(Api.getPostBySlug(slug));
                getPostSlugRequest
                    .then(res => {
                        if (res.statusCode == 200) {
                            if (res.data.length != 0) {
                                var postID = res.data[0].id;
                                var openLinkCount = swan.getStorageSync('openLinkCount') || 0;
                                if (openLinkCount > 4) {
                                    swan.redirectTo({
                                        url: '../detail/detail?id=' + postID
                                    })
                                } else {
                                    swan.navigateTo({
                                        url: '../detail/detail?id=' + postID
                                    })
                                    openLinkCount++;
                                    swan.setStorageSync('openLinkCount', openLinkCount);
                                }
                            } else {
                                var minAppType = config.getMinAppType;
                                var url = '../webpage/webpage'
                                if (minAppType == "0") {
                                    url = '../webpage/webpage';
                                    swan.navigateTo({
                                        url: url + '?url=' + href
                                    })
                                } else {
                                    self.copyLink(href);
                                }


                            }

                        }

                    }).catch(res => {
                        console.log(response.data.message);
                    })
            }
        }

    },
    //获取评论
    fetchCommentData: function () {
        var self = this;
        let args = {};
        args.postId = self.data.postID;
        args.limit = pageCount;
        args.page = self.data.page;
        self.setData({
            isLoading: true
        })
        var getCommentsRequest = bdRequest.getRequest(Api.getCommentsReplay(args));
        getCommentsRequest
            .then(response => {
                if (response.statusCode == 200) {
                    if (response.data.data.length < pageCount) {
                        self.setData({
                            isLastPage: true
                        });
                    }
                    if (response.data) {
                        self.setData({
                            commentsList: [].concat(self.data.commentsList, response.data.data)
                        });
                    }

                }

            })
            .catch(response => {
                console.log(response.data.message);

            }).finally(function () {

                self.setData({
                    isLoading: false
                });

            });
    },
    //显示或隐藏功能菜单
    ShowHideMenu: function () {
        this.setData({
            isShow: !this.data.isShow,
            isLoad: false,
            menuBackgroup: !this.data.false
        })
    },
    //点击非评论区隐藏功能菜单
    hiddenMenubox: function () {
        this.setData({
            isShow: false,
            menuBackgroup: false
        })
    },
    //底部刷新
    loadMore: function (e) {
        var self = this;
        if (!self.data.isLastPage) {
            self.setData({
                page: self.data.page + 1
            });
            console.log('当前页' + self.data.page);
            this.fetchCommentData();
        } else {
            swan.showToast({
                title: '没有更多内容',
                mask: false,
                duration: 1000
            });
        }
    },
    // 回复
    replay: function (e) {
        var self = this;
        var id = e.target.dataset.id;
        var name = e.target.dataset.name;
        var userid = e.target.dataset.userid;
        var toFromId = e.target.dataset.formid;
        var commentdate = e.target.dataset.commentdate;
        isFocusing = true;
        if (self.data.enableComment == "1") {
            self.setData({
                parentID: id,
                placeholder: "回复" + name + ":",
                focus: true,
                userid: userid,
                toFromId: toFromId,
                commentdate: commentdate
            });

        }
        console.log('toFromId', toFromId);
        console.log('replay', isFocusing);
    },
    onReplyBlur: function (e) {
        var self = this;
        console.log('onReplyBlur', isFocusing);
        if (!isFocusing) {
            {
                const text = e.detail.value.trim();
                if (text === '') {
                    self.setData({
                        parentID: "0",
                        placeholder: "评论...",
                        userid: "",
                        toFromId: "",
                        commentdate: ""
                    });
                }

            }
        }
        console.log(isFocusing);
    },
    // 回复
    onRepleyFocus: function (e) {
        var self = this;
        isFocusing = false;
        console.log('onRepleyFocus', isFocusing);
        if (!self.data.focus) {
            self.setData({
                focus: true
            })
        }


    },
    //提交评论
    formSubmit: function (e) {
        var self = this;
        var comment = e.detail.value.inputComment;
        var parent = self.data.parentID;
        var postID = e.detail.value.inputPostID;
        var formId = e.detail.formId;
        if (formId == "the formId is a mock one") {
            formId = "";

        }
        var userid = self.data.userid;
        var toFromId = self.data.toFromId;
        var commentdate = self.data.commentdate;
        if (comment.length === 0) {
            self.setData({
                'dialog.hidden': false,
                'dialog.title': '提示',
                'dialog.content': '没有填写评论内容。'

            });
        } else {
            if (self.data.openid) {
                var name = self.data.userInfo.nickName;
                var author_url = self.data.userInfo.avatarUrl;
                var email = self.data.openid + "@qq.com";
                var openid = self.data.openid;
                var fromUser = self.data.userInfo.nickName;
                var data = {
                    post: postID,
                    author_name: name,
                    author_email: email,
                    content: comment,
                    author_url: author_url,
                    parent: parent,
                    openid: openid,
                    userid: userid,
                    formId: formId
                };
                var url = Api.wechatAddComment();
                var postCommentRequest = bdRequest.postRequest(url, data);
                postCommentRequest
                    .then(res => {
                        if (res.statusCode == 200) {
                            if (res.data.status == '200') {
                                self.setData({
                                    content: '',
                                    parentID: "0",
                                    userid: 0,
                                    placeholder: "评论...",
                                    focus: false,
                                    commentsList: []

                                });
                                console.log(res.data.message);
                                if (parent != "0" && !util.getDateOut(commentdate) && toFromId != "") {
                                    var useropenid = res.data.useropenid;
                                    var data = {
                                        openid: useropenid,
                                        postid: postID,
                                        template_id: self.data.replayTemplateId,
                                        form_id: toFromId,
                                        total_fee: comment,
                                        fromUser: fromUser,
                                        flag: 3,
                                        parent: parent
                                    };

                                    url = Api.sendMessagesUrl();
                                    var sendMessageRequest = bdRequest.postRequest(url, data);
                                    sendMessageRequest.then(response => {
                                        if (response.data.status == '200') {
                                            console.log(response.data.message);
                                            // wx.navigateBack({
                                            //     delta: 1
                                            // })

                                        } else {
                                            console.log(response.data.message);

                                        }

                                    });

                                }
                                console.log(res.data.code);
                                var commentCounts = parseInt(self.data.total_comments) + 1;
                                self.setData({
                                    total_comments: commentCounts,
                                    commentCount: "有" + commentCounts + "条评论"

                                });
                            } else if (res.data.status == '500') {
                                self.setData({
                                    'dialog.hidden': false,
                                    'dialog.title': '提示',
                                    'dialog.content': '评论失败，请稍后重试。'

                                });
                            }
                        } else {

                            if (res.data.code == 'rest_comment_login_required') {
                                self.setData({
                                    'dialog.hidden': false,
                                    'dialog.title': '提示',
                                    'dialog.content': '需要开启在WordPress rest api 的匿名评论功能！'

                                });
                            } else if (res.data.code == 'rest_invalid_param' && res.data.message.indexOf('author_email') > 0) {
                                self.setData({
                                    'dialog.hidden': false,
                                    'dialog.title': '提示',
                                    'dialog.content': 'email填写错误！'

                                });
                            } else {
                                console.log(res.data.code)
                                self.setData({
                                    'dialog.hidden': false,
                                    'dialog.title': '提示',
                                    'dialog.content': '评论失败,' + res.data.message

                                });
                            }
                        }
                    }).then(response => {
                        //self.fetchCommentData(self.data); 
                        self.setData({
                            page: 1,
                            commentsList: [],
                            isLastPage: false

                        })
                        self.onReachBottom();
                        //self.fetchCommentData();
                        setTimeout(function () {
                            swan.showToast({
                                title: '评论发布成功',
                                icon: 'success',
                                duration: 900,
                                success: function () { }
                            })
                        }, 900);
                    }).catch(response => {
                        console.log(response)
                        self.setData({
                            'dialog.hidden': false,
                            'dialog.title': '提示',
                            'dialog.content': '评论失败,' + response

                        });
                    })
            } else {
                Auth.checkSession(self, 'isLoginNow');

            }

        }

    },

    agreeGetUser: function (e) {
        console.log(23344566)
        let self = this;
        Auth.checkAgreeGetUser(e, app, self, '0');;

    },
    // 关闭登陆面板
    closeLoginPopup() {
        this.setData({
            isLoginPopup: false
        });
    },
    // 打开登陆
    openLoginPopup() {
        this.setData({
            isLoginPopup: true
        });
    },
    confirm: function () {
        this.setData({
            'dialog.hidden': true,
            'dialog.title': '',
            'dialog.content': ''
        })
    },
    downimageTolocal: function () {
        var self = this;
        self.ShowHideMenu();
        // wx.showLoading({
        //     title: "正在生成海报",
        //     mask: true,
        // });
        var postid = self.data.detail.id;
        var title = self.data.detail.title.rendered;
        var path = "pages/detail/detail?id=" + postid;
        var excerpt = util.removeHTML(self.data.detail.excerpt.rendered);
        var postImageUrl = "";
        var posterImagePath = "";
        var qrcodeImagePath = "";
        var flag = false;
        var imageInlocalFlag = false;
        var domain = config.getDomain;
        var downloadFileDomain = config.getDownloadFileDomain;

        var fristImage = self.data.detail.post_medium_image;

        //获取文章首图临时地址，若没有就用默认的图片,如果图片不是request域名，使用本地图片
        if (fristImage) {
            var n = 0;
            for (var i = 0; i < downloadFileDomain.length; i++) {

                if (fristImage.indexOf(downloadFileDomain[i].domain) != -1) {
                    n++;
                    break;
                }
            }
            if (n > 0) {
                imageInlocalFlag = false;
                postImageUrl = fristImage;

            } else {
                postImageUrl = config.getPostImageUrl;
                posterImagePath = postImageUrl;
                imageInlocalFlag = true;
            }

        } else {
            postImageUrl = config.getPostImageUrl;
            posterImagePath = postImageUrl;
            imageInlocalFlag = true;
        }

        console.log(postImageUrl);
        var data = {
            postid: postid,
            path: path

        };
        var url = Api.creatPoster();
        var qrcodeUrl = "";
        var posterQrcodeUrl = Api.getPosterQrcodeUrl() + "qrcode-" + postid + ".png";
        //生成二维码
        var creatPosterRequest = bdRequest.postRequest(url, data);
        creatPosterRequest.then(response => {
            if (response.statusCode == 200) {
                if (response.data.status == '200') {
                    const downloadTaskQrcodeImage = swan.downloadFile({
                        url: posterQrcodeUrl,
                        success: res => {
                            if (res.statusCode === 200) {
                                qrcodeImagePath = res.tempFilePath;
                                console.log("二维码图片本地位置：" + res.tempFilePath);
                                if (!imageInlocalFlag) {
                                    const downloadTaskForPostImage = swan.downloadFile({
                                        url: postImageUrl,
                                        success: res => {
                                            if (res.statusCode === 200) {
                                                posterImagePath = res.tempFilePath;
                                                console.log("文章图片本地位置：" + res.tempFilePath);
                                                flag = true;
                                                if (posterImagePath && qrcodeImagePath) {
                                                    self.createPosterLocal(posterImagePath, qrcodeImagePath, title, excerpt);
                                                }
                                            } else {
                                                console.log(res);
                                                swan.hideLoading();
                                                swan.showToast({
                                                    title: "生成海报失败...",
                                                    mask: true,
                                                    duration: 2000
                                                });
                                                return false;


                                            }
                                        }
                                    });
                                    downloadTaskForPostImage.onProgressUpdate((res) => {
                                        console.log('下载文章图片进度：' + res.progress)

                                    })
                                } else {
                                    if (posterImagePath && qrcodeImagePath) {
                                        self.createPosterLocal(posterImagePath, qrcodeImagePath, title, excerpt);
                                    }
                                }
                            } else {
                                console.log(res);
                                //wx.hideLoading();
                                flag = false;
                                swan.showToast({
                                    title: "生成海报失败...",
                                    mask: true,
                                    duration: 2000
                                });
                                return false;
                            }
                        }
                    });
                    downloadTaskQrcodeImage.onProgressUpdate((res) => {
                        console.log('下载二维码进度', res.progress)
                    })
                } else {
                    console.log(response);
                    //wx.hideLoading();
                    flag = false;
                    swan.showToast({
                        title: "生成海报失败...",
                        mask: true,
                        duration: 2000
                    });
                    return false;
                }
            } else {
                console.log(response);
                //wx.hideLoading();
                flag = false;
                swan.showToast({
                    title: "生成海报失败...",
                    mask: true,
                    duration: 2000
                });
                return false;
            }

        });


    },
    //将canvas转换为图片保存到本地，然后将路径传给image图片的src
    createPosterLocal: function (postImageLocal, qrcodeLoal, title, excerpt) {
        var that = this;
        swan.showLoading({
            title: "正在生成海报",
            mask: true,
        });
        var context = swan.createCanvasContext('mycanvas');
        context.setFillStyle('#ffffff'); //填充背景色
        context.fillRect(0, 0, 600, 970);
        context.drawImage(postImageLocal, 0, 0, 600, 400); //绘制首图
        context.drawImage(qrcodeLoal, 210, 670, 180, 180); //绘制二维码
        //context.drawImage(that.data.logo, 350, 740, 130, 130);//画logo
        //const grd = context.createLinearGradient(30, 690, 570, 690)//定义一个线性渐变的颜色
        //grd.addColorStop(0, 'black')
        //grd.addColorStop(1, '#118fff')
        //context.setFillStyle(grd)
        context.setFillStyle("#959595");
        context.setFontSize(20);
        context.setTextAlign('center');
        context.fillText("阅读文章，请长按识别二维码", 300, 900);
        //context.setStrokeStyle(grd)
        context.setFillStyle("#959595");
        // context.beginPath()//分割线
        // context.moveTo(30, 690)
        // context.lineTo(570, 690)
        // context.stroke();
        // this.setUserInfo(context);//用户信息        
        util.drawTitleExcerpt(context, title, excerpt); //文章标题
        context.draw();
        //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
        setTimeout(function () {
            swan.canvasToTempFilePath({
                canvasId: 'mycanvas',
                success: function (res) {
                    var tempFilePath = res.tempFilePath;
                    // that.setData({
                    //     imagePath: tempFilePath,
                    //     maskHidden: "none"
                    // });
                    swan.hideLoading();
                    console.log("海报图片路径：" + res.tempFilePath);
                    that.modalView.showModal({
                        title: '保存至相册可以分享到朋友圈',
                        confirmation: false,
                        confirmationText: '',
                        inputFields: [{
                            fieldName: 'posterImage',
                            fieldType: 'Image',
                            fieldPlaceHolder: '',
                            fieldDatasource: res.tempFilePath,
                            isRequired: false,
                        }],
                        confirm: function (res) {
                            console.log(res)
                            //用户按确定按钮以后会回到这里，并且对输入的表单数据会带回
                        }
                    })


                },
                fail: function (res) {
                    console.log(res);
                }
            });
        }, 900);
    }
})